import { defineEventHandler } from 'h3'
import redis from '../util/redis'
import { recordLog } from '../util/log'

export default defineEventHandler(async (event) => {
  try {
    // INCR will create the key if not exists and increment atomically
    const next = await redis.incr('visits:count')
    await recordLog(event as any, { message: `visits: incremented to ${next}`, userId: 0 })
    return { count: Number(next) }
  } catch (err) {
    event.node.res.statusCode = 500
    await recordLog(event as any, { message: `visits: failed to increment ${String(err)}`, userId: 0 })
    return { status: 500, message: 'failed to increment visits', error: String(err) }
  }
})
